﻿using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
using Manas.Core.Extensions;

namespace MovieModels
{
    public class FormatHelper
    {
        static string fileString = Directory.GetCurrentDirectory() + "\\CommonlyUsedMovieKeys.xml";
        static XDocument doc = XDocument.Load(fileString);
        static Regex regExExtract = new Regex(@"([a-zA-Z0-9]+)", RegexOptions.Compiled);
        static IEnumerable<string> commonfileNames;
        static IEnumerable<string> CommonfileNames
        {
            get
            {
                if (commonfileNames.IsNull())
                    commonfileNames = doc.Element("MovieStrings").Elements("Key").Select(x => x.Value);
                return commonfileNames;
            }
        }
        
        /// <summary>
        /// Formats the name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static string GetFormattedMovieName(string name)
        {
            //name = name.Split('-').COu;
            MatchCollection matchedStrings = regExExtract.Matches(name);
            string returnString = string.Empty;
            for (int i = 0; i < matchedStrings.Count; i++)
            {
                if (IsNonMovieKeyword(matchedStrings[i].Value) || IsYearString(matchedStrings[i].Value))
                    continue;
                returnString += " " + matchedStrings[i];
            }
            return returnString.Trim();
        }

        /// <summary>
        /// Determines whether [is non movie keyword] [the specified name string].
        /// </summary>
        /// <param name="nameString">The name string.</param>
        /// <returns>
        ///   <c>true</c> if [is non movie keyword] [the specified name string]; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsNonMovieKeyword(string nameString)
        {
            nameString = nameString.Trim();
            var result = CommonfileNames.Any(x => Regex.IsMatch(nameString, x, RegexOptions.IgnoreCase));
            return result;
        }

        /// <summary>
        /// Isies the year string.
        /// </summary>
        /// <param name="nameString">The name string.</param>
        /// <returns>
        ///   <c>true</c> if [is year string] [the specified name string]; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsYearString(string nameString)
        {
            nameString = nameString.Trim();
            string CurDate = DateTime.Now.ToString("yyyy");
            Regex yearRegx = new Regex(@"[12][0-9][0-9][0-9]");
            return yearRegx.IsMatch(nameString) && CurDate.CompareTo(nameString) >= 0;
        }
    }
}
